<?php
class AdModel extends CommonModel {
    public function __construct(){
        parent::__construct();
    }

    //获取广告类型的数据
    //生成下拉框
    function query_ad_type(){
        return $list = M("Adtype")->where("status=1")->order("id desc")->select();           
    }
    //获取新闻列表数据
    public function queryAdList($p , $per_page = 100 , $where = array() ){
        if($p <=0 ){
            $p = 1 ;
        }
        $getwhere = " where 1 = 1 " ;
        if(isset($where['typename']) &&  $where['typename'] ){
            $getwhere.=" AND a.typename like '%{$where['typename']}%' ";
        }
        if(isset($where['name']) &&  $where['name'] ){
            $getwhere.=" AND a.name like '%{$where['name']}%' ";
        }
        if( in_array($where['status'] , array('1', '0' ) ) ){
            $getwhere.=" AND a.status = '{$where['status']}' ";
        }
        if( in_array($where['type'] , array('1', '0' ) ) ){
            $getwhere.=" AND a.type = '{$where['type']}' ";
        }
        if($where['typeid'] > 0  ){
        	$getwhere.=" AND a.ad_type = '{$where['typeid']}' ";
        }
        //echo $getwhere ;
        import('Library.Page' , APP_PATH);
        $limit = ($p-1)*$per_page;
        $limit.=",{$per_page}";
        $where = '1= 1 ';
        $sql_count = "select count(*) as c from ".C("DB_PREFIX")."ad as a left join ".C("DB_PREFIX")."adtype as b on a.ad_type = b.id {$getwhere}" ;
        $count_data = M()->query($sql_count);
        $total = $count_data[0]['c'];

        $page = new Page($total,$per_page);
        $page_string =  $page->show();
        
        $sql = "select a.*  ,b.typename  from ".C("DB_PREFIX")."ad as a left join ".C("DB_PREFIX")."adtype as b on a.ad_type = b.id {$getwhere} order by a.addtime desc  limit {$limit}" ;
    //  echo $sql;
        $list = M()->query($sql);
        
        if($list){
            foreach($list AS $k1 => $v1 ){
                if($v1['status'] == 1 ){
                    $list[$k1]['status'] = "<input type='radio' name='status[{$k1}]' checked value='1' onclick='editStatus({$v1['id']} , 1 )'>开启<input type='radio' name='status[{$k1}]' value='0' onclick='editStatus({$v1['id']} , 0 )'>关闭";
                }else{
                    $list[$k1]['status'] = "<span style='color:red'><input type='radio' name='status[{$k1}]' value='1' onclick='editStatus({$v1['id']} , 1 )' >开启<input type='radio' name='status[{$k1}]' checked value='0' onclick='editStatus({$v1['id']} , 0 )'>关闭</span>";

                }
                
                $list[$k1]['typename'] = msubstr($v1['typename'],0,20);
                $list[$k1]['addtime'] = isset($v1['addtime'])?date("Y-m-d H:i",$v1['addtime']):'' ;
                $list[$k1]['begin_date'] = ($v1['begin_date'] > 0 )?date("Y-m-d H:i:s",$v1['begin_date']):'无' ;
                $list[$k1]['end_date'] = ($v1['end_date'] > 0 )?date("Y-m-d H:i:s",$v1['end_date']):'无' ;
                if(file_exists("./Data/Upload/Ad/{$v1['pic']}") && $v1['pic'] != '' ){
                    $pic_url = C("upload_domain")."/Ad/{$v1['pic']}";;
                    $list[$k1]['pic'] = "<img src='{$pic_url}' width='80' height='80'>";
                }else{
                    $list[$k1]['pic'] = '图片没有' ;
                }
                if(file_exists("./Data/Upload/Ad/{$v1['pic2']}") && $v1['pic2'] != '' ){
                    $pic_url = C("upload_domain")."/Ad/{$v1['pic2']}";;
                    $list[$k1]['pic2'] = "<img src='{$pic_url}' width='80' height='80'>";
                }else{
                    $list[$k1]['pic2'] = '图片没有' ;
                }
                $list[$k1]['type'] = ($v1['type'] == 0 )?"图片广告":'<font color="red">文字广告</font>';

            }
            
        }
        return array('list'=>$list , 'page_string'=>$page_string);
    }
    //根据广告类别ID查询信息
    public function getAdDataById($id){
        return M("Ad")->where("id='{$id}'")->find();
    }
    //插入广告类型
    function insertAd(){
        if($_POST['info']['name'] == '' ){
            return array('status'=>false  , 'message'=>'广告名称不可以为空' );
        }
        $_POST['info']['addtime'] = time();
        if($_POST['info']['begin_date'] != 0){
            $_POST['info']['begin_date'] = strtotime($_POST['info']['begin_date']);
        }
        if($_POST['info']['end_date'] != 0){
            $_POST['info']['end_date'] = strtotime($_POST['info']['end_date']);
        }
       
        $d = M("Ad");
        $_POST['info']['add_person'] = $this->username ; 
        if($row=$d->create($_POST['info'])){
            if($d->add()){
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "添加广告{$_POST['info']['name']}成功" );
                return array('status'=>1 , 'message'=>'添加成功');
            }else{
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "添加广告{$_POST['info']['name']}失败" );
                return array('status'=>0 , 'message'=>'服务器繁忙请稍后');
            }
        }else{
            write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败" );
            return array('status'=>0 , 'message'=>'数据创建失败');
        }
    }
    //修改广告类型
    function editAd(){
        if($_POST['info']['name'] == '' ){
            return array('status'=>false  , 'message'=>'广告名称不可为空' );
        }
        if($_POST['info']['begin_date'] != 0 ){
            $_POST['info']['begin_date'] = strtotime($_POST['info']['begin_date']);
        }
        if($_POST['info']['end_date'] != 0){
            $_POST['info']['end_date'] = strtotime($_POST['info']['end_date']);
        }
        $d = M("Ad");
        if($row=$d->create($_POST['info'])){
          // print_r($_POST['info']);
            if($d->save()){
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "修改广告{$_POST['info']['name']}成功" );
                return array('status'=>1 , 'message'=>'修改成功');
            }else{
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "修改广告{$_POST['info']['name']}失败" );
                return array('status'=>0 , 'message'=>'服务器繁忙请稍后');
            }
        }else{
            write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败" );
            return array('status'=>0 , 'message'=>'数据创建失败');
        }
    }   
    //修改状态
    public function doStatus($data = array() ){
        $d = M("Ad");
        $num = $d->where("id = '{$data['id']}'")->save(array('status'=>$data['status']));
        $sql = $d->getLastSql() ;
        if($num >=1 ){
            write_action_log($sql, getModuleAction() , $this->username , get_client_ip() , 1 , "修改广告id:{$data['id']}状态成功" );
            return array('status'=>1 , 'message'=>'修改成功');
        }
        write_action_log($sql, getModuleAction() , $this->username , get_client_ip() , 0 , "修改广告id:{$data['id']}状态失败" );
            return array('status'=>0 , 'message'=>'修改失败你可能没有修改数据');
    }
    //上传图片
    public function upload_ad_pic(){
            import('ORG.Net.UploadFile');
            $upload = new UploadFile();// 实例化上传类
            $upload->maxSize  = 3145728 ;// 设置附件上传大小
            $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->savePath =  __ROOTPATH__.'/Data/Upload/Ad/';// 设置附件上传目录
            $upload->autoSub = true;//使用子目录保存上传文件
            $upload->subType = 'date';//使用日期模式创建子目录
            $upload->dateFormat = 'Ymd';//设置子目录日期格式
            if(!$upload->upload()) {// 上传错误提示错误信息
                return array('status' => 0 , 'message'=> $upload->getErrorMsg());
            }else{// 上传成功 获取上传文件信息
                $info =  $upload->getUploadFileInfo();
            }
            return array('status'=>1 , 'message'=>'success' , 'pic'=>$info[0]['savename'] ) ;
            
    }
    //删除广告
    public function del($data = array() ){
        $info = M("Ad")->where("id={$data['id']}")->find();
        if(!$info){
            return array('status'=> 0 ,'message'=>'参数错误') ;
        }
        $num = M("Ad")->where("id={$data['id']}")->delete(); 
        $sql = M("Ad")->getLastSql();

        if($num){
            
            write_action_log($sql, getModuleAction(),$this->username,get_client_ip(),1,"删除广告--{$info['name']}--成功");
            return array('status'=> 1 ,'message'=>'操作成功') ;
        }else{
            write_action_log($sql, getModuleAction(),$this->username,get_client_ip(),0,"删除广告--{$info['name']}--失败");
            return array('status'=> 0 ,'message'=>'网络繁忙请稍后') ;
        }
    }
    
      
}
